﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_SYSTEM;
using ERP_RORZE_TOOL.Tool.UserControls;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_TOOL.Tool.Forms
{
    public partial class frm_BrokenAdd : DevExpress.XtraEditors.XtraForm
    {
        private ucBroken parent;
        private ucBorrow parentBorrow;
        private bool firstLoadFromBorrow = true;
        public string ToolId;
        public string MachineId;
        public bool FromBorrow;
        private DataTable dataTable;
        private bool dropDown;
        AutoCompleteStringCollection itemToolID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemMachineID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemMistakeID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemStatusID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemPartID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemProcessStatus = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemRotateID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemToKindID = new AutoCompleteStringCollection();
        private LogUtils log;

        public frm_BrokenAdd(ucBroken fBroken = null, ucBorrow fBorrow = null, bool isFromBorrow = false)
        {
            InitializeComponent();
            btAdd.Image = ERP_RORZE_TOOL.Properties.Resources.add;
            btCancel.Image = ERP_RORZE_TOOL.Properties.Resources.cancel;
            parent = fBroken;
            parentBorrow = fBorrow;
            FromBorrow = isFromBorrow;
            cmbMachine.LostFocus += cmbMachine_LostFocus;
            cmbToolID.LostFocus += cmbToolID_LostFocus;
            cmbPart.LostFocus += cmbPart_LostFocus;
            cmbToKind.LostFocus += cmbToKind_LostFocus;
            cmbMistake.LostFocus += cmbMistake_LostFocus;
            cmbStatus.LostFocus += cmbStatus_LostFocus;
            cmbProcessStatus.LostFocus += cmbProcessStatus_LostFocus;
            cmbRotate.LostFocus += cmbRotate_LostFocus;
            //this.CancelButton = this.btCancel;
            this.ActiveControl = cmbToolID;
            log = new LogUtils();

        }

        void cmbRotate_LostFocus(object sender, EventArgs e)
        {
            if (cmbRotate.Items.Count <= 0)
            {
                foreach (string s in cmbRotate.AutoCompleteCustomSource)
                {
                    if (cmbRotate.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbRotate.Text = s;
                        break;
                    }
                }

            }
        }

        void cmbProcessStatus_LostFocus(object sender, EventArgs e)
        {
            if (cmbProcessStatus.Items.Count <= 0)
            {
                foreach (string s in cmbProcessStatus.AutoCompleteCustomSource)
                {
                    if (cmbProcessStatus.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbProcessStatus.Text = s;
                        break;
                    }
                }

            }
        }

        void cmbStatus_LostFocus(object sender, EventArgs e)
        {
            if (cmbStatus.Items.Count <= 0)
            {
                foreach (string s in cmbStatus.AutoCompleteCustomSource)
                {
                    if (cmbStatus.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbStatus.Text = s;
                        break;
                    }
                }

            }
        }

        void cmbMistake_LostFocus(object sender, EventArgs e)
        {
            if (cmbMistake.Items.Count <= 0)
            {
                foreach (string s in cmbMistake.AutoCompleteCustomSource)
                {
                    if (cmbMistake.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbMistake.Text = s;
                        break;
                    }
                }

            }
        }

        void cmbToKind_LostFocus(object sender, EventArgs e)
        {
            if (cmbToKind.Items.Count <= 0)
            {
                foreach (string s in cmbToKind.AutoCompleteCustomSource)
                {
                    if (cmbToKind.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbToKind.Text = s;
                        break;
                    }
                }

            }

            string sql = "SELECT * from [333_Tool] " +
                         " WHERE [333_Tool].ToolID = N'" + cmbToKind.Text + "'";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                txtToKindName.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.ToolName].ToString();
            }
            else
            {
                txtToKindName.Text = string.Empty;
            }
        }

        void cmbPart_LostFocus(object sender, EventArgs e)
        {
            if (cmbPart.Items.Count <= 0)
            {
                foreach (string s in cmbPart.AutoCompleteCustomSource)
                {
                    if (cmbPart.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbPart.Text = s;
                        break;
                    }
                }

            }

            string sql = "SELECT [242_Part].PartNo, [242_PartData].MaterialID, [242_Customer].CustomerName " +
                         "FROM ([242_Part] INNER JOIN [242_Customer] " +
                         "  ON [242_Part].CustomerID=[242_Customer].CustomerID) " +
                         "INNER JOIN [242_PartData] ON [242_Part].PartNo=[242_PartData].PartID " +
                         " WHERE [242_Part].PartNo = N'" + cmbPart.Text + "'";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                txtMaterialID.Text = dataTable.Rows[0][ToolConstants.Entities.Part.FieldName.MaterialID].ToString();
                txtCustomerID.Text = dataTable.Rows[0]["CustomerName"].ToString();
            }
            else
            {
                txtMaterialID.Text = string.Empty;
                txtCustomerID.Text = string.Empty;
            }
        }

        void cmbToolID_LostFocus(object sender, EventArgs e)
        {
            if (cmbToolID.Items.Count <= 0)
            {
                foreach (string s in cmbToolID.AutoCompleteCustomSource)
                {
                    if (cmbToolID.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbToolID.Text = s;
                        break;
                    }
                }

            }

            string sql = "SELECT DISTINCT [333_Tool].ToolID, [333_Tool].ToolName, [333_Tool].MakerToolName, " +
                         "[333_Tool].Price, [333_Tool].FrequencyID, [333_Tool].ToolGroupID, [333_Tool].SafeQty, " +
                         "[333_Import].MakerID, [333_Import].SupplierID, [333_Import].PriceJPY, max([333_Import].Date) AS LastOfDate " +
                         "FROM [333_Tool] LEFT JOIN [333_Import] ON [333_Tool].ToolID = [333_Import].ToolID " +
                         "GROUP BY [333_Tool].ToolID, [333_Tool].ToolName, [333_Tool].MakerToolName, " +
                         "[333_Tool].Price, [333_Tool].FrequencyID, [333_Tool].ToolGroupID, [333_Tool].SafeQty, " +
                         "[333_Import].MakerID, [333_Import].SupplierID, [333_Import].PriceJPY " +
                         "HAVING [333_Tool].ToolID = N'" + cmbToolID.Text + "';";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                txtToolName.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.ToolName].ToString();
                txtMakerToolName.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.MakerToolName].ToString();
                txtFrequencyID.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.FrequencyID].ToString();
                txtToolGroupID.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.ToolGroupID].ToString();
                txtSafeQty.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.SafeQty].ToString();
                txtMakerID.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.MakerID].ToString();
                txtSupplierID.Text = dataTable.Rows[0][ToolConstants.Entities.Import.FieldName.SupplierID].ToString();
                txtPriceJPY.Text = dataTable.Rows[0][ToolConstants.Entities.Import.FieldName.PriceJPY].ToString();
                txtPrice.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.Price].ToString();
            }
            else
            {
                txtToolName.Text = string.Empty;
                txtMakerToolName.Text = string.Empty;
                txtFrequencyID.Text = string.Empty;
                txtToolGroupID.Text = string.Empty;
                txtSafeQty.Text = string.Empty;
                txtMakerID.Text = string.Empty;
                txtSupplierID.Text = string.Empty;
                txtPriceJPY.Text = string.Empty;
                txtPrice.Text = string.Empty;
            }
        }

        void cmbMachine_LostFocus(object sender, EventArgs e)
        {
            if (cmbMachine.Items.Count <= 0)
            {
                foreach (string s in cmbMachine.AutoCompleteCustomSource)
                {
                    if (cmbMachine.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbMachine.Text = s;
                        break;
                    }
                }

            }
        }

        private void XtraForm1_Load(object sender, EventArgs e)
        {


            if (FromBorrow)
            {
                dtpTDate.Value = DateTime.Today;
                BindDataMistake();
                BindDataMachine();
                BindDataStatus();
                BindDataPart();
                BindDataProcessStatus();
                BindDataRotate();
                BindDataFromBorrow();
                BindDataToKind();
                rdDelete.Checked = true;
                firstLoadFromBorrow = false;
            }
            else
            {
                dtpTDate.Value = DateTime.Today;
                BindDataTool();
                BindDataMistake();
                BindDataMachine();
                BindDataStatus();
                BindDataPart();
                BindDataProcessStatus();
                BindDataRotate();
                BindDataToKind();
                rdDelete.Checked = true;
            }

            cmbToolID.Focus();

        }

        private void btTAdd_Click_1(object sender, EventArgs e)
        {
            AddTool();
        }

        private void btTCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        private void rdDelete_CheckedChanged(object sender, EventArgs e)
        {
            lblSelecTool.Enabled = false;
            cmbToKind.Text = string.Empty;
            cmbToKind.Enabled = false;
        }

        private void rdChangekind_CheckedChanged(object sender, EventArgs e)
        {
            lblSelecTool.Enabled = true;
            cmbToKind.Enabled = true;
        }

        private void cmbMachine_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (cmbMachine.SelectedItem != cmbMachine.Items[0] && !FromBorrow)
            //{
            //    string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
            //    string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.Text + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
            //    string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
            //    string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

            //    int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

            //    if (number <= 0)
            //        MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineNotBorrow, cmbMachine.Text, cmbToolID.Text), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    else
            //    {
            //        MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineBorrow, cmbMachine.Text, cmbToolID.Text, number.ToString()), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    }
            //}
            //else if (cmbMachine.SelectedItem != cmbMachine.Items[0] && FromBorrow && !firstLoadFromBorrow)
            //{
            //    string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
            //    string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.Text + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
            //    string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
            //    string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

            //    int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

            //    if (number <= 0)
            //        MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineNotBorrow, cmbMachine.Text, cmbToolID.Text), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    else
            //    {
            //        MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineBorrow, cmbMachine.Text, cmbToolID.Text, number.ToString()), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    }
            //}
        }

        private void cmbMistake_DropDown(object sender, EventArgs e)
        {
            dropDown = true;
            System.Windows.Forms.ComboBox combo = sender as System.Windows.Forms.ComboBox;
            combo.AutoCompleteMode = AutoCompleteMode.None;

            if (combo.Items.Count <= 0)
            {
                Cursor.Current = Cursors.WaitCursor;
                switch (combo.Name)
                {
                    case "cmbToolID":
                        foreach (var item in itemToolID)
                        {
                            cmbToolID.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbMachine":
                        foreach (var item in itemMachineID)
                        {
                            cmbMachine.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbMistake":
                        foreach (var item in itemMistakeID)
                        {
                            cmbMistake.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbStatus":
                        foreach (var item in itemStatusID)
                        {
                            cmbStatus.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbPart":
                        foreach (var item in itemPartID)
                        {
                            cmbPart.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbProcessStatus":
                        foreach (var item in itemProcessStatus)
                        {
                            cmbProcessStatus.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbRotate":
                        foreach (var item in itemRotateID)
                        {
                            cmbRotate.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbToKind":
                        foreach (var item in itemToKindID)
                        {
                            cmbToKind.Items.Add(item.ToString());

                        }
                        break;

                }
                Cursor.Current = Cursors.Default;

            }
        }

        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            // Add controls for which Arrow keys => focus is not required.
            if ((!dropDown && (ActiveControl is TextBox || ActiveControl is System.Windows.Forms.ComboBox || ActiveControl is System.Windows.Forms.DateTimePicker)))
            {
                switch (keyData)
                {
                    case Keys.Up:
                    case Keys.Down:

                        bool forward = (keyData == Keys.Down);
                        if (this.ProcessTabKey(forward))
                        {
                            return true;
                        }

                        break;
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void frm_BrokenAdd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.D)
                {
                    btAdd.Focus();
                    this.btAdd.PerformClick();
                }
            }
            else if (e.KeyCode == Keys.End)
            {
                btAdd.Focus();
            }
            else if (e.KeyCode == Keys.Home)
            {
                dtpTDate.Focus();
            }
        }

        #region Private methods

        private bool GetDataTool(Broken o)
        {
            #region Check valid

            DataTable dtCheck;

            if (Utilities.IsNullOrEmpty(dtpTDate.Text))
            {
                MessageBox.Show(ToolConstants.Message.Broken.DateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                dtpTDate.Focus();
                return false;
            }


            if (Utilities.IsNullOrEmpty(cmbToolID.Text))
            {
                MessageBox.Show(ToolConstants.Message.Broken.ToolIDCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbToolID.Focus();
                return false;
            }

            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Tool] where [ToolID]=N'" + cmbToolID.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.ToolIDInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbToolID.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbMachine.Text))
            {
                MessageBox.Show(ToolConstants.Message.Broken.MachineCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbMachine.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [222_Machine] where [MachineID]=N'" + cmbMachine.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.MachineInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbMachine.Focus();
                return false;
            }


            if (Utilities.IsNullOrEmpty(cmbMistake.Text))
            {
                MessageBox.Show(ToolConstants.Message.Broken.MistakeCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbMistake.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Mistake] where [MistakeID]=N'" + cmbMistake.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.MistakeInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbMistake.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbStatus.Text))
            {
                MessageBox.Show(ToolConstants.Message.Broken.StatusCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbStatus.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_ToolStatus] where [StatusName]=N'" + cmbStatus.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.MistakeInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbStatus.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(txtLossNo.Text.Trim()))
            {
                MessageBox.Show(ToolConstants.Message.Broken.LossNoCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtLossNo.Focus();
                return false;
            }


            if (Utilities.IsNullOrEmpty(cmbPart.Text))
            {
                MessageBox.Show(ToolConstants.Message.Broken.PartCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbPart.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [242_Part] where [PartNo]=N'" + cmbPart.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.PartInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbPart.Focus();
                return false;
            }


            if (Utilities.IsNullOrEmpty(txtQuantity.Text.Trim()))
            {
                MessageBox.Show(ToolConstants.Message.Broken.QuantityCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtQuantity.Focus();
                return false;
            }

            if (int.Parse(txtQuantity.Text) <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.QuantityMustGreaterZero, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtQuantity.Focus();
                return false;

            }

            if (int.Parse(txtQuantity.Text) > 0)
            {
                string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.Text + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
                string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);


                if (number < int.Parse(txtQuantity.Text))
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.WrongQuantity, cmbMachine.Text, number.ToString(), txtQuantity.Text), ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtQuantity.Focus();
                    return false;
                }

            }

            if (Utilities.IsNullOrEmpty(cmbProcessStatus.Text))
            {
                MessageBox.Show(ToolConstants.Message.Broken.ProcessStatusCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbProcessStatus.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_ProcessStatus] where [ProcessStatusID]=N'" + cmbProcessStatus.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.ProcessStatusInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbProcessStatus.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbRotate.Text))
            {
                MessageBox.Show(ToolConstants.Message.Broken.RotateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbRotate.Focus();
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Rotate] where [RotateID]=N'" + cmbRotate.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.RotateInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbRotate.Focus();
                return false;
            }

            //if(Utilities.IsNullOrEmpty(txtStandardSpeed.Text.Trim()))
            //{
            //    MessageBox.Show(ToolConstants.Message.Broken.StandardSpeedCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return false;
            //}

            //if(Utilities.IsNullOrEmpty(txtRealitySpeed.Text.Trim()))
            //{
            //    MessageBox.Show(ToolConstants.Message.Broken.RealitySpeedCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return false;
            //}

            if (rdChangekind.Checked)
            {

                if (Utilities.IsNullOrEmpty(cmbToKind.Text))
                {
                    MessageBox.Show(ToolConstants.Message.Broken.ToKindCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Tool] where [ToolID]='" + cmbToKind.Text + "'");
                if (dtCheck.Rows.Count <= 0)
                {
                    MessageBox.Show(ToolConstants.Message.Broken.ToKindInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cmbToKind.Focus();
                    return false;
                }
            }
            #endregion

            o.Date = dtpTDate.Value.Date;
            o.ToolID = cmbToolID.Text.ToString();
            o.MachineID = cmbMachine.Text.ToString();
            o.MistakeID = cmbMistake.Text.ToString();
            o.StatusName = cmbStatus.Text.ToString();
            o.LossNo = txtLossNo.Text;
            o.PartNo = cmbPart.Text.ToString();
            o.Quantity = int.Parse(txtQuantity.Text);
            o.ProcessStatusID = cmbProcessStatus.Text.ToString();
            o.RotateID = cmbRotate.Text.ToString();
            o.StandardSpeed = txtStandardSpeed.Text;
            o.RealitySpeed = txtRealitySpeed.Text;
            if (rdChangekind.Checked)
            {
                o.Process = ToolConstants.Configuration.ProcessStatus.TrueStr;
                o.ToKind = cmbToKind.Text.ToString();
            }
            else
            {
                o.Process = ToolConstants.Configuration.ProcessStatus.FalseStr;
                o.ToKind = "";

            }
            o.Note = memoTNote.Text;

            return true;
        }

        private void BindDataTool()
        {
            ToolHelper helper = new ToolHelper(new Tools());
            //dt = helper.GetAllByToolType();
            //DataRow row = dt.NewRow();


            //row[ToolConstants.Entities.Tool.FieldName.FullName] = "Select...";
            //row[ToolConstants.Entities.Tool.FieldName.ToolID] = null;
            //dt.Rows.InsertAt(row, 0);

            //cmbToolID.DataSource = dt;
            //cmbToolID.DisplayMember = ToolConstants.Entities.Tool.FieldName.FullName;
            //cmbToolID.ValueMember = ToolConstants.Entities.Tool.FieldName.ToolID;

            //cmbToolID.SelectedItem = cmbToolID.Items[0];


            //foreach (DataRow row in helper.GetAll().Rows)
            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemToolID.Add(row[ToolConstants.Entities.Tool.FieldName.ToolID].ToString());

            }
            cmbToolID.AutoCompleteCustomSource = itemToolID;
        }

        private void BindDataMistake()
        {
            MistakeHelper helper = new MistakeHelper(new Mistake());
            //DataTable dt = helper.GetAll();
            //DataRow row = dt.NewRow();

            //row[ToolConstants.Entities.Mistake.FieldName.FullName] = "Select...";
            //row[ToolConstants.Entities.Mistake.FieldName.MistakeID] = null;
            //dt.Rows.InsertAt(row, 0);

            //cmbMistake.DataSource = dt;
            //cmbMistake.DisplayMember = ToolConstants.Entities.Mistake.FieldName.FullName;
            //cmbMistake.ValueMember = ToolConstants.Entities.Mistake.FieldName.MistakeID;

            //cmbMistake.SelectedItem = cmbMistake.Items[0];

            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemMistakeID.Add(row[ToolConstants.Entities.Mistake.FieldName.MistakeID].ToString());

            }
            cmbMistake.AutoCompleteCustomSource = itemMistakeID;
        }

        private void BindDataMachine()
        {
            MachineHelper helper = new MachineHelper(new Machine());
            //DataTable dt = helper.GetAll();
            //DataRow row = dt.NewRow();

            //row[ToolConstants.Entities.Machine.FieldName.FullName] = "Select...";
            //row[ToolConstants.Entities.Machine.FieldName.MachineID] = null;
            //dt.Rows.InsertAt(row, 0);

            //cmbMachine.DataSource = dt;
            //cmbMachine.DisplayMember = ToolConstants.Entities.Machine.FieldName.FullName;
            //cmbMachine.ValueMember = ToolConstants.Entities.Machine.FieldName.MachineID;
            //cmbMachine.SelectedItem = cmbMachine.Items[0];

            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemMachineID.Add(row[ToolConstants.Entities.Machine.FieldName.MachineID].ToString());

            }
            cmbMachine.AutoCompleteCustomSource = itemMachineID;
        }

        private void BindDataStatus()
        {
            ToolStatusHelper helper = new ToolStatusHelper(new ToolStatus());
            //DataTable dt = helper.GetAll();
            //DataRow row = dt.NewRow();


            //row[ToolConstants.Entities.ToolStatus.FieldName.StatusName] = "Select...";
            //dt.Rows.InsertAt(row, 0);

            //cmbStatus.DataSource = dt;
            //cmbStatus.DisplayMember = ToolConstants.Entities.ToolStatus.FieldName.StatusName;
            //cmbStatus.ValueMember = ToolConstants.Entities.ToolStatus.FieldName.StatusName;

            //cmbStatus.SelectedItem = cmbStatus.Items[0];

            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemStatusID.Add(row[ToolConstants.Entities.ToolStatus.FieldName.StatusName].ToString());

            }
            cmbStatus.AutoCompleteCustomSource = itemStatusID;
        }

        private void BindDataPart()
        {
            PartHelper helper = new PartHelper(new Part());

            //row[ToolConstants.Entities.Part.FieldName.FullName] = "Select...";
            //row[ToolConstants.Entities.Part.FieldName.PartNo] = DBNull.Value;
            //dt.Rows.InsertAt(row, 0);
            //cmbPart.DataSource = dt;
            //cmbPart.DisplayMember = ToolConstants.Entities.Part.FieldName.FullName;
            //cmbPart.ValueMember = ToolConstants.Entities.Part.FieldName.PartNo;
            //cmbPart.SelectedItem = cmbPart.Items[0];

            //foreach (DataRow row in helper.GetAll().Rows)
            //{
            //    cmbPart.Items.Add(row[ToolConstants.Entities.Part.FieldName.PartNo].ToString());

            //}

            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemPartID.Add(row[ToolConstants.Entities.Part.FieldName.PartNo].ToString());

            }
            cmbPart.AutoCompleteCustomSource = itemPartID;
        }

        private void BindDataProcessStatus()
        {
            ProcessStatusHelper helper = new ProcessStatusHelper(new ProcessStatus());
            //DataTable dt = helper.GetAll();
            //DataRow row = dt.NewRow();

            //row[ToolConstants.Entities.ProcessStatus.FieldName.FullName] = "Select...";
            //row[ToolConstants.Entities.ProcessStatus.FieldName.ProcessStatusID] = null;
            //dt.Rows.InsertAt(row, 0);

            //cmbProcessStatus.DataSource = dt;
            //cmbProcessStatus.DisplayMember = ToolConstants.Entities.ProcessStatus.FieldName.FullName;
            //cmbProcessStatus.ValueMember = ToolConstants.Entities.ProcessStatus.FieldName.ProcessStatusID;
            //cmbProcessStatus.SelectedItem = cmbProcessStatus.Items[0];

            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemProcessStatus.Add(row[ToolConstants.Entities.ProcessStatus.FieldName.ProcessStatusID].ToString());

            }
            cmbProcessStatus.AutoCompleteCustomSource = itemProcessStatus;
        }

        private void BindDataRotate()
        {
            RotateHelper helper = new RotateHelper(new Rotate());
            //DataTable dt = helper.GetAll();
            //DataRow row = dt.NewRow();

            //row[ToolConstants.Entities.Rotate.FieldName.FullName] = "Select...";
            //row[ToolConstants.Entities.Rotate.FieldName.RotateID] = null;
            //dt.Rows.InsertAt(row, 0);

            //cmbRotate.DataSource = dt;
            //cmbRotate.DisplayMember = ToolConstants.Entities.Rotate.FieldName.FullName;
            //cmbRotate.ValueMember = ToolConstants.Entities.Rotate.FieldName.RotateID;
            //cmbRotate.SelectedItem = cmbRotate.Items[0];

            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemRotateID.Add(row[ToolConstants.Entities.Rotate.FieldName.RotateID].ToString());

            }
            cmbRotate.AutoCompleteCustomSource = itemRotateID;
        }

        private void BindDataToKind()
        {

            ToolHelper helper = new ToolHelper(new Tools());
            //dtKind = helper.GetAllByToolType();
            //row = dtKind.NewRow();

            //row[ToolConstants.Entities.Tool.FieldName.FullName] = "Select...";
            //row[ToolConstants.Entities.Tool.FieldName.ToolID] = null;
            //dtKind.Rows.InsertAt(row, 0);

            //cmbToKind.DataSource = dtKind;
            //cmbToKind.DisplayMember = ToolConstants.Entities.Tool.FieldName.FullName;
            //cmbToKind.ValueMember = ToolConstants.Entities.Tool.FieldName.ToolID;

            //cmbToKind.SelectedItem = cmbToKind.Items[0];

            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemToKindID.Add(row[ToolConstants.Entities.Tool.FieldName.ToolID].ToString());

            }
            cmbToKind.AutoCompleteCustomSource = itemToKindID;



        }

        private void AddTool()
        {
            BrokenHelper helper = new BrokenHelper(new Broken());
            ToolHelper helperTool = new ToolHelper(new Tools());
            ImportHelper helperImport = new ImportHelper(new Import());
            JustNewHelper helperJN = new JustNewHelper(new JustNew());
            DataTable dtCheck = new DataTable();
            if (GetDataTool(helper.ValueObject))
            {
                //get data to tool
                helperTool.ValueObject.ToolID = helper.ValueObject.ToKind;
                helperTool.ValueObject.ToolName = txtToKindName.Text;
                helperTool.ValueObject.MakerToolName = txtMakerToolName.Text;
                helperTool.ValueObject.Price = decimal.Parse(txtPrice.Text);
                helperTool.ValueObject.FrequencyID = txtFrequencyID.Text;
                helperTool.ValueObject.ToolGroupID = txtToolGroupID.Text;
                helperTool.ValueObject.SafeQty = int.Parse(txtSafeQty.Text);
                helperTool.ValueObject.MakerID = txtMakerID.Text;
                dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Tool] where [ToolID]='" + helperTool.ValueObject.ToolID + "'");

                //get data to import
                helperImport.ValueObject.Date = helper.ValueObject.Date;
                helperImport.ValueObject.ToolID = helper.ValueObject.ToKind;
                helperImport.ValueObject.MakerID = txtMakerID.Text;
                helperImport.ValueObject.SupplierID = txtSupplierID.Text;
                helperImport.ValueObject.Quantity = helper.ValueObject.Quantity;
                helperImport.ValueObject.PriceJPY = decimal.Parse(txtPriceJPY.Text);
                helperImport.ValueObject.Note = helper.ValueObject.Process;

                //get data to JustNew
                helperJN.ValueObject.Date = helper.ValueObject.Date;
                helperJN.ValueObject.ToolID = helper.ValueObject.ToKind;
                helperJN.ValueObject.Quantity = helper.ValueObject.Quantity;
                helperJN.ValueObject.Note = helper.ValueObject.Process;

                if (helper.ValueObject.Process.Equals(ToolConstants.Configuration.ProcessStatus.TrueStr))
                {
                    if (helper.Insert() > 0 && helperImport.Insert() > 0 && helperJN.Insert() > 0)
                    {
                        //write Log
                        log.Table = LogConstant.Table.ToolCutting.Broken;
                        log.Task = LogConstant.Task.Insert;
                        log.Description = helper.ValueObject.ToolID;
                        log.WriteLog();

                        if (dtCheck.Rows.Count <= 0)
                        {
                            helperTool.Insert();
                        }
                        if (Utilities.MessageConfirmationYesNo(ToolConstants.Message.AddSuccessAndQuestion))
                        {
                            ResetForm();
                        }
                        else
                        {
                            this.Close();
                        }

                    }
                    else
                    {
                        Utilities.MessageErrorOk(ToolConstants.Message.AddFailed);
                    }
                }
                else
                {
                    if (helper.Insert() > 0)
                    {
                        if (Utilities.MessageConfirmationYesNo(ToolConstants.Message.AddSuccessAndQuestion))
                        {
                            ResetForm();
                        }
                        else
                        {
                            this.Close();
                        }
                    }
                    else
                    {
                        Utilities.MessageErrorOk(ToolConstants.Message.AddFailed);
                    }
                }


                if (parent != null)
                {
                    parent._action = 0;
                    parent.BindDatatoGrid();
                }
                if (FromBorrow)
                {
                    parentBorrow.BindDatatoBroken();
                }

            }
        }

        private void ResetForm()
        {
            dtpTDate.Value = DateTime.Now;
            cmbToolID.Text = string.Empty;
            cmbMachine.Text = string.Empty;
            cmbMistake.Text = string.Empty;
            cmbStatus.Text = string.Empty;
            cmbPart.Text = string.Empty;
            cmbProcessStatus.Text = string.Empty;
            cmbRotate.Text = string.Empty;
            txtLossNo.Text = "";
            memoTNote.Text = "";
            txtQuantity.Text = "";
            txtStandardSpeed.Text = "";
            txtRealitySpeed.Text = "";
            rdDelete.Checked = true;

            txtMaterialID.Text = string.Empty;
            txtCustomerID.Text = string.Empty;

            txtToKindName.Text = string.Empty;

            txtToolName.Text = string.Empty;
            txtMakerToolName.Text = string.Empty;
            txtFrequencyID.Text = string.Empty;
            txtToolGroupID.Text = string.Empty;
            txtSafeQty.Text = string.Empty;
            txtMakerID.Text = string.Empty;
            txtSupplierID.Text = string.Empty;
            txtPriceJPY.Text = string.Empty;
            txtPrice.Text = string.Empty;

            cmbToolID.Focus();
        }

        private void BindDataFromBorrow()
        {
            BindDataTool();

            cmbToolID.Text = ToolId;
            cmbMachine.Text = MachineId;

            //if (cmbToolID.Text == null)
            //{
            //    cmbToolID.SelectedItem = cmbToolID.Items[0];
            //}

            //if (cmbMachine.SelectedItem == null)
            //{
            //    cmbMachine.SelectedItem = cmbMachine.Items[0];
            //}
            //int instockAtpresent = CheckInputTool();
            //lblStatus.Visible = true;
            //lblStatus.Text = string.Format(ToolConstants.Message.Borrow.ToolInStock, cmbToolID.SelectedValue, instockAtpresent.ToString());


        }
        #endregion

        private void cmbRotate_DropDownClosed(object sender, EventArgs e)
        {
            dropDown = false;
            ((System.Windows.Forms.ComboBox)sender).AutoCompleteMode = AutoCompleteMode.Append;
        }

        private void cmbMachine_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (cmbMachine.Text != string.Empty && !FromBorrow)
                {
                    string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                    string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.Text + "' and " +
                                   ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
                    string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                    string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                    int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

                    if (number <= 0)
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.Broken.MachineNotBorrow, cmbMachine.Text, cmbToolID.Text),
                            ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                    {
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.Broken.MachineBorrow, cmbMachine.Text, cmbToolID.Text,
                                          number.ToString()), ToolConstants.Form.MessageBox.Warning,
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else if (cmbMachine.Text != string.Empty && FromBorrow && !firstLoadFromBorrow)
                {
                    string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                    string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.Text + "' and " +
                                   ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
                    string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                    string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                    int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

                    if (number <= 0)
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.Broken.MachineNotBorrow, cmbMachine.Text, cmbToolID.Text),
                            ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                    {
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.Broken.MachineBorrow, cmbMachine.Text, cmbToolID.Text,
                                          number.ToString()), ToolConstants.Form.MessageBox.Warning,
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

    }
}